﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using LogLib;

namespace QrCode
{
    class ScanCode
    {
        public static SerialPortHelper com;
        public static string barcodeMsg;

        public static byte[] cmdStart = new byte[] { 0x16, 0x54, 0x0D }; //开始扫描指令
        public static byte[] cmdStop = new byte[] { 0x16, 0x55, 0x0D }; //停止扫描指令

        public static bool InitCom(string strCom, int baudrate)
        {
            bool ret = false;
            if (com == null)
            {
                try
                {
                    com = new SerialPortHelper();
                    com.serialPort.PortName = strCom;
                    com.serialPort.BaudRate = baudrate;
                    com.serialPort.DataBits = 8;
                    com.serialPort.StopBits = StopBits.One;
                    com.serialPort.Parity = Parity.None;
                    //com.serialPort.ReadTimeout = readTimeout;
                    com.Open();
                    if (com.IsOpen)
                    {
                        com.DataReceived += new EventHandler_Comm(comm_DataReceived);
                        ret = true;
                    }
                }
                catch
                { }
            }
            else
                ret = true;
            return ret;
        }

        public static void comm_DataReceived(byte[] readBuffer)
        {
            if (readBuffer.Length > 0)
            {
                barcodeMsg = Encoding.Default.GetString(readBuffer);
                Log.Write("扫描到的二维码：" + barcodeMsg);
            }
        }

        public static bool SendMsg(byte[] cmd, string strcom, int baudrate)
        {
            bool ret = false;
            ret = InitCom(strcom, baudrate);
            if (com.IsOpen)
            {
                try
                {
                    com.WritePort(cmd, 0, cmd.Length);
                    ret = true;
                }
                catch
                { }
            }
            return ret;
        }

        public static void CloseCom()
        {
            if (com == null)
            {
                return;
            }
            if (com.IsOpen)
            {
                com.Close();
            }
        }
    }
}
